package kubevirt

import (
	"gluenet/internal/agent/driver/virtdriver/options"
	"os/exec"
	"strconv"
)

type KubevirtDriver struct{}

func NewKubevirtDirver() (*KubevirtDriver, error) {
	return new(KubevirtDriver), nil
}

func (kd *KubevirtDriver) executeCmd(args ...string) error {
	cmd := exec.Command(`virtctl`, args...)
	// cmdStr := fmt.Sprint(cmd.Path, " ", strings.Join(args, " "))
	// fmt.Println(cmdStr)
	return cmd.Run()
}

func (kd *KubevirtDriver) StartVMI(virtualMachineInstanceName string, opts options.StartVmiOptions) error {
	args := []string{`start`, virtualMachineInstanceName}

	if opts.NameSpace != `` {
		args = append(args, `-n`, opts.NameSpace)
	}

	return kd.executeCmd(args...)
}

func (kd *KubevirtDriver) StopVMI(virtualMachineInstanceName string, opts options.StopVmiOptions) error {
	args := []string{`stop`, virtualMachineInstanceName}

	if opts.NameSpace != `` {
		args = append(args, `-n`, opts.NameSpace)
	}

	return kd.executeCmd(args...)
}

func (kd *KubevirtDriver) executeExposeCmd(resourceType, name string, opts options.ExposeVmiOptions) error {
	if err := opts.ExposeOptionsCheck(); err != nil {
		return err
	}

	args := []string{`expose`, resourceType, name, `--name`, opts.Name, `--port`, strconv.Itoa(int(opts.Port))}

	if opts.NameSpace != `` {
		args = append(args, `-n`, opts.NameSpace)
	}

	if opts.Type != `` {
		args = append(args, `--type`, opts.Type)
	}

	if opts.TargetPort != 0 {
		args = append(args, `--target-port`, strconv.Itoa(int(opts.TargetPort)))
	}

	return kd.executeCmd(args...)
}

func (kd *KubevirtDriver) ExposeVM(virtualMachineName string, opts options.ExposeVmiOptions) error {
	return kd.executeExposeCmd(`vm`, virtualMachineName, opts)
}

func (kd *KubevirtDriver) ExposeVMI(virtualMachineInstanceName string, opts options.ExposeVmiOptions) error {
	return kd.executeExposeCmd(`vmi`, virtualMachineInstanceName, opts)
}

func (kd *KubevirtDriver) ExposeVMIs(virtualMachineInstanceReplicasetName string, opts options.ExposeVmiOptions) error {
	return kd.executeExposeCmd(`vmirs`, virtualMachineInstanceReplicasetName, opts)
}
